package oauth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import oauth.constant.MyConstants;
import oauth.model.AccessToken;
import oauth.model.OAuthResponse;
import oauth.model.RefreshToken;
import oauth.utils.EBayEnvironment;
import oauth.utils.OAuth2Api;

@Controller
public class MyController {

	@RequestMapping("/getTokenFromOath")
	@ResponseBody
	public String getTokenFromOath(String ebayId) {
		AccessToken accessToken = MyConstants.accessTokenMap.get(ebayId);
		if(accessToken!=null) {
			return accessToken.getToken();
		}
		return "";
	}
	
	
	@GetMapping("/")
	public String goOauth() {
		return "index";
	}

	@RequestMapping("/getAuthUrl")
	public ModelAndView getAuthUrl(String ebayId) {
		OAuth2Api oauth2Api = new OAuth2Api();
		List<String> scopeList = new ArrayList<>();
		scopeList.add("https://api.ebay.com/oauth/api_scope");
		scopeList.add("https://api.ebay.com/oauth/api_scope/sell.finances");
		scopeList.add("https://api.ebay.com/oauth/api_scope/sell.fulfillment");
		scopeList.add("https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly");

		String authorization_url = oauth2Api.generateUserAuthorizationUrl(EBayEnvironment.PRODUCTION, scopeList,
				Optional.of(ebayId));
		// oauth2Api.generateUserAuthorizationUrl(EBayEnvironment.PRODUCTION, scopeList,
		// Optional.empty());
		System.out.println(authorization_url);
		ModelAndView mav = new ModelAndView();
		mav.setViewName("index");
		mav.addObject("authorization_url", authorization_url);
		return mav;
	}

	@RequestMapping("/getToken")
	public String getToken(String code, String state) {
		OAuth2Api oauth2Api = new OAuth2Api();
		try {
			OAuthResponse oauth2Response = oauth2Api.exchangeCodeForAccessToken(EBayEnvironment.PRODUCTION, code);
			System.out.println(oauth2Response);
			AccessToken accessToken = oauth2Response.getAccessToken().get();
			System.out.println(accessToken.getToken());
			System.out.println(accessToken.getExpiresOn());
			System.out.println(accessToken.getExpiresIn());
			RefreshToken refreshToken = oauth2Response.getRefreshToken().get();
			MyConstants.accessTokenMap.put(state, accessToken);
			MyConstants.refreshTokenMap.put(state, refreshToken);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return "index";
	}
	
	
	
	
	
}
